﻿using System;
using System.IO;
using Luban;
using SimpleJSON;
using UnityEngine;

namespace Gp.Scripts.Core
{
    public class ExcelTableManager
    {
        private static readonly Lazy<ExcelTableManager> _instance = 
            new Lazy<ExcelTableManager>(() =>
            {
                var instance = new ExcelTableManager();
                instance.Init();
                return instance;
            });
    
        public static ExcelTableManager Instance => _instance.Value;
        
        private ExcelTableManager() { }
        
        private ExcelTables TableData { get; set; }

        public void Init()
        {
            var tablesCtor = typeof(ExcelTables).GetConstructors()[0];

            var loaderReturnType = tablesCtor.GetParameters()[0].ParameterType.GetGenericArguments()[1];
            // 根据cfg.Tables的构造函数的Loader的返回值类型决定使用json还是ByteBuf Loader
            System.Delegate loader = loaderReturnType == typeof(ByteBuf)
                ? new System.Func<string, ByteBuf>(LoadByteBuf)
                : new System.Func<string, JSONNode>(LoadJson);

            TableData = (ExcelTables) tablesCtor.Invoke(new object[] {loader});
        }

        private static JSONNode LoadJson(string file)
        {
            return JSON.Parse(File.ReadAllText(
                $"{Application.dataPath}/{ConstApplication.CONFIG_TABLE_PATH}/Json/{file}.json",
                System.Text.Encoding.UTF8));
        }

        private static ByteBuf LoadByteBuf(string file)
        {
            return new ByteBuf(
                File.ReadAllBytes($"{Application.dataPath}/{ConstApplication.CONFIG_TABLE_PATH}/Byte/{file}.bytes"));
        }


        public T GetByType<T>() where T : class, IConfigTable
        {
            return TableData.GetByType<T>();
        }
    }
}